package cn.liuyang.tinyioc.context;

import cn.liuyang.tinyioc.beans.BeanDefinition;
import cn.liuyang.tinyioc.beans.factory.AbstractBeanFactory;
import cn.liuyang.tinyioc.beans.factory.AutowiredCapableBeanFactory;
import cn.liuyang.tinyioc.beans.io.ResourceLoader;
import cn.liuyang.tinyioc.beans.xml.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * Created by liuyang on 2018/4/8.
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext{

    private String configLocation;

    public ClassPathXmlApplicationContext(String configLocation) throws Exception {
        this(configLocation,new AutowiredCapableBeanFactory());

    }

    public ClassPathXmlApplicationContext(String configLocation,AbstractBeanFactory beanFactory) throws Exception {
        super(beanFactory);
        this.configLocation = configLocation;
        refresh();
    }


    @Override
    public void refresh() throws Exception {
        // 1. 读取xml并初始化bean
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
        // 1.1 加载BeanDefinition
        xmlBeanDefinitionReader.loadBeanDefinitions(configLocation);

        // 2. 装配bean
        // 2.1 遍历注册bean
        for (Map.Entry<String, BeanDefinition> beanDefinitionEntry :
                xmlBeanDefinitionReader.getRegistry().entrySet()) {
            beanFactory.registryBeanDefinition(beanDefinitionEntry.getKey(),beanDefinitionEntry.getValue());
        }
    }
}
